package com.tul.vapp.servicecenter.utils;

import com.tul.vapp.servicecenter.client.ReportRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.StringReader;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 配置中心的工具类
 * @author wwxiang
 * @since 2017/12/28.
 */
public class ConfigUtil {

	/**
	 * 日志
	 */
	private static final Logger LOGGER = LoggerFactory.getLogger(ReportRepository.class);

	/**
	 * 将string解析为Properties
	 * 
	 * @param content string内容
	 * @return Properties
	 * @throws IOException e
	 */
	public static Properties parse(String content) throws IOException {
		StringReader reader = new StringReader(content);
		Properties properties = new Properties();
		properties.load(reader);
		return properties;
	}

	/**
	 * 将pros格式化为Map<String, String>
	 * 
	 * @param props Properties
	 * @return 键值对
	 */
	public static Map<String, String> format(Properties props) {
		Map<String, String> result = new ConcurrentHashMap<>();
		for (Object key : props.keySet()) {
			String keyStr = (String) key;
			result.put(keyStr, props.getProperty(keyStr));
		}
		return result;
	}

	/**
	 * 将String格式化为Map<String, String>
	 *
	 * @param content content
	 * @return 键值对
	 */
	public static Map<String, String> format(String content) {
		Properties props = null;
		try {
			props = parse(content);
		} catch (IOException e) {
			LOGGER.error("zookeeper content parse error", e);
		}
		Map<String, String> result = new ConcurrentHashMap<>();
		if (props == null) {
			return result;
		}
		for (Object key : props.keySet()) {
			String keyStr = (String) key;
			result.put(keyStr, props.getProperty(keyStr));
		}
		return result;
	}

	/**
	 * 将map转化为zk中可写入的string
	 *
	 * @param data data
	 * @return str
	 */
	public static String parseMapToStr(Map<String, String> data) {
		String zkData = null;
		if (data == null) {
			zkData = "";
		} else {
			StringBuilder builder = new StringBuilder();
			for (Map.Entry<String, String> entry : data.entrySet()) {
				builder.append(entry.getKey()).append("=").append(entry.getValue()).append("\n");
			}
			zkData = builder.toString();
		}
		return zkData;
	}
}
